

import UIKit
//命名空间 在同一项目下  必须导入AFNetworing  命名空间
import AFNetworking

private let HomeCellID = "HomeCellID"


class HomeTableViewController: BaseTableViewController {

    private lazy var statues = [Status]()




    override func viewDidLoad() {
        super.viewDidLoad()

        if !userLogin {
            visitorLoginView?.setWithInfo("关注一些人，回这里看看有什么惊喜", imageName: nil)
            return
        }
        prepareTableView()

        loadData()
    }

    //注册cell
    private func prepareTableView() {
        tableView.registerClass(StatusCell.self, forCellReuseIdentifier: HomeCellID)

        tableView.estimatedRowHeight = 200

        tableView.rowHeight = UITableViewAutomaticDimension


        tableView.separatorStyle = .None

        refreshControl = UIRefreshControl()
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: .ValueChanged)
        tableView.tableFooterView = indicatorView



    }
    private lazy var indicatorView: UIActivityIndicatorView = {
let indicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray)
        indicator.startAnimating()
        return indicator




    }()




    //MARK : 加载数据
    @objc private func loadData(){

        refreshControl?.beginRefreshing()

        var since_id = 0

        var max_id = 0

        if indicatorView.isAnimating() {
            since_id = 0
            max_id = statues.first?.id ?? 0

        }else {
          max_id = 0
            since_id = statues.first?.id ?? 0

        }

        StatusListViewModel.loadData(since_id, max_id : max_id ){ (statues) -> () in
            self.refreshControl?.endRefreshing()

            guard let list = statues else {

        SVProgressHUD.showErrorWithStatus(AppErrorTip)
                return

            }

            if since_id > 0 {



                self.statues = list + self.statues

            }else if max_id > 0 {

                self.statues +=  list

            self.indicatorView.stopAnimating()
            } else {
self.statues = list
        }
            self.tableView.reloadData()



        }

    }

    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        return statues.count
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //如果使用这个方法 获取cell 并且不是在 sb / xib 就需要程序员手动注册cell
        let cell  = tableView.dequeueReusableCellWithIdentifier(HomeCellID, forIndexPath: indexPath) as! StatusCell
        
        cell.status = statues[indexPath.row]

        if indexPath.row == statues.count - 1 && !indicatorView.isAnimating() {

indicatorView.startAnimating()
            loadData()
        }
        
        return cell
        
    }
    
    
}
